// pages/homework/bindinfo/bindinfo.js
import http from '../../../utils/request2.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    studentNumber: '',
    studentName: '',
    parentPhone: '',
    parentStudent: '',
    pickercontent: '',
    index: 0,
    phoneNumber: '',
    wxcode: '',
    userinfo: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ wxcode: wx.getStorageSync('wxCode') })
    try {
      // 从缓存中获取
      let teacherUserInfo = wx.getStorageSync('teacherUserInfo');
      console.log(teacherUserInfo, '什么');

      teacherUserInfo.gradeListStr = teacherUserInfo.gradeList.join(',');
      teacherUserInfo.classListStr = teacherUserInfo.classList.join(',');
      teacherUserInfo.teacherRoleStr = teacherUserInfo.teacherRole.join(',');

      if (teacherUserInfo) {
        this.setData({
          userinfo: teacherUserInfo
        });
      }
    } catch (e) {
      console.error('获取teacherUserInfo 出错:', e);
    }
  },
  //绑定教师
  async bindTeacher() {
    let { index } = this.data
    let { openid, unionId } = JSON.parse(wx.getStorageSync('wxopenid'))

    let phoneNumber = this.data.userinfo.phoneNumber
    //  let phoneNumber = this.data.phoneNumber
    if (!phoneNumber) {
      wx.showToast({
        title: '请先绑定手机号',
        icon: 'none'
      })
      return
    }
    // console.info(index)
    let obj = {
      openId: openid,
      unionId: unionId ? unionId : '',
      identify: index,
      phoneNumber: phoneNumber
    }
    let that = this
    let options = {
      url: '/open/system/system/teacherBind',
      method: 'post',
      data: obj,
      header: { "content-type": "application/json;charset=UTF-8" }
    }
    let res = await http(options)  // Now this await is valid
    if (res && res.data.code == 200) {
      console.info('ddddd')
      wx.switchTab({
        url: '/pages/homework/homeworkSituation/homeworkSituation',
      })
    }
  },
  bindPickerChange(e) {
    const index = e.detail.value;
    const selectedItem = this.data.studentrole[index];
    this.setData({
      index,
      pickercontent: selectedItem.name // 更新显示文本
    });
  },
  //学生信息管理
  studentinfolink() {
    wx.switchTab({
      url: '/pages/homework/userinfo/userinfo',
    })
  },
  //获取学生学号
  bindStudentNumber(e) {
    this.setData({
      studentNumber: e.detail.value
    })
  },
  //获取学生姓名
  bindStudentName(e) {
    this.setData({
      studentName: e.detail.value
    })
  },
  //获取家长手机号
  bindparentPhone(e) {
    this.setData({
      parentPhone: e.detail.value
    })
  },
  //获取学生家长关系
  bindparentChildren(e) {
    this.setData({
      parentStudent: e.detail.value
    })
  },
  //获取手机号
  // async onGetPhoneNumber(e) {
  //   let {wxcode} = this.data
  //   if (e.detail.errMsg === "getPhoneNumber:ok") {
  //     const { encryptedData, iv } = e.detail;
  //       wx.login({
  //         success: async (res) => {
  //           // console.info(res.code)  // Add async here
  //             // const code = res.code; // 临时登录凭证
  //             console.info(res.code)
  //             let that = this
  //             let options = {
  //                 url:'/open/system/getPhoneNumberByDecode',
  //                 method:'get',
  //                 data:{encryptedData:encryptedData,iv:iv,code:res.code},
  //                 header:{"content-type":"application/json;charset=UTF-8"}
  //             }
  //             let ress = await http(options)  // Now this await is valid
  //             console.info(ress,'ress')
  //             if(ress&&ress.data.code==200){
  //               this.setData({phoneNumber:JSON.parse(ress.data.msg).phoneNumber})
  //             }else{
  //                 this.setData({attention:ress.data.mes})
  //             }
  //         }
  //     });
  //   } else {
  //     console.log('用户拒绝授权');
  //   }
  // },
  async onGetPhoneNumber(e) {
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      const { encryptedData, iv } = e.detail;

      wx.login({
        success: async (res) => {
          console.info('wx.login code:', res.code);
          try {
            let options = {
              url: '/open/system/getPhoneNumberByDecode',
              method: 'get',
              data: {
                encryptedData,
                iv,
                code: res.code
              },
              header: { "content-type": "application/json;charset=UTF-8" }
            };
            let ress = await http(options);
            // console.info('后端解密结果:', ress);

            if (ress && ress.data.code == 200) {
              let phoneNumber = JSON.parse(ress.data.msg).phoneNumber;
              this.setData({ phoneNumber });
            } else {
              wx.showToast({
                title: ress.data.msg || '获取手机号失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('获取手机号出错:', error);
            wx.showToast({
              title: '请求异常',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('wx.login 失败:', err);
          wx.showToast({
            title: '微信登录失败',
            icon: 'none'
          });
        }
      });
    } else {
      console.log('用户拒绝授权');
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})